// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { userInfo, gameData } = event
  
  try {
    // 更新用户基本信息
    if (userInfo) {
      await db.collection('users').where({
        _openid: wxContext.OPENID
      }).update({
        data: {
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl,
          gender: userInfo.gender,
          lastUpdateTime: db.serverDate()
        }
      })
    }
    
    // 更新游戏数据
    if (gameData) {
      const user = await db.collection('users').where({
        _openid: wxContext.OPENID
      }).get()
      
      if (user.data.length > 0) {
        const currentUser = user.data[0]
        const updateData = {
          gameCount: currentUser.gameCount + (gameData.gameCount || 0),
          winCount: currentUser.winCount + (gameData.winCount || 0),
          totalScore: currentUser.totalScore + (gameData.score || 0),
          lastUpdateTime: db.serverDate()
        }
        
        // 更新最高分
        if (gameData.score && (!currentUser.highestScore || gameData.score > currentUser.highestScore)) {
          updateData.highestScore = gameData.score
        }
        
        await db.collection('users').where({
          _openid: wxContext.OPENID
        }).update({
          data: updateData
        })
      }
    }
    
    return {
      success: true
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 